<template>
  <div style="padding: 20px;padding-top: 0;">
    <HuilanBasicToolbar style="margin-top: 20px">
      <el-button type="success" size="small" :disabled="trainDisabled" @click.stop="submitTrain">提交训练
      </el-button>
      <el-button type="warning" size="small" @click="ImportAggregate">
        导入数据集
      </el-button>
      <el-button type="primary" size="small" :loading="loadingBtn.export" @click="exportDataSit">
        导出数据集
      </el-button>
      <el-button type="danger" size="small" @click="handleMouseEnter">
        训练记录
      </el-button>
      <el-button type="" size="small" :loading="loadingBtn.del" @click="delDataSit">
        删除数据集
      </el-button>
    </HuilanBasicToolbar>
    <HuilanBasicSearchbar :model="searchForm" :fields="searchFieldList" @reset="searchReset" @search="searchChange">
    </HuilanBasicSearchbar>
    <avue-crud v-model="form" :option="option" :data="data" ref="crud" @row-save="rowSave" @row-update="rowUpdate"
      @row-del="rowDel" @selection-change="selectionChange" :page.sync="page" @current-change="currentChange"
      @size-change="sizeChange">
      <template v-slot:menu="scope">
        <HuilanBasicActionTool :actions="getRowActions(scope.row)"
          @command="handleRowCommand($event, scope.row, scope.index)" />
      </template>
    </avue-crud>
    <QSGDrawer :title="dataInTitle" :fullscreen="false" :size="600" append-to-body :visible.sync="trainingRecordsVisible"
      :wrapperClosable="false" :before-close="beforeClose">
      <avue-form :option="optionForm" ref="form" v-model="form" :upload-preview="uploadPreview"
        :upload-before="uploadBefore" :upload-after="uploadAfter" @submit="submit">
        <template slot="aggregateText">
          <span>请先 <a :href="downUrl" download><span
                style="color: #409eff;cursor: pointer;">下载模板</span></a>，填写完成后上传（支持xls、xlsx格式文件）</span>
        </template>
      </avue-form>
      <template v-slot:footer>
        <el-button size="small" type="primary" @click.stop="formSave">确 定</el-button>
        <el-button size="small" @click.stop="formClose">取 消</el-button>
      </template>
    </QSGDrawer>
    <HuilanDialog title="训练记录" :visible.sync="visible" append-to-body width="1000px" custom-class="upload-image-dialog">
      <avue-crud v-model="form" :option="optionReport" :data="trainData" ref="crud" @row-save="rowSave"
        @row-update="rowUpdate" @row-del="rowDel" :loading="trainLoding">
      </avue-crud>
    </HuilanDialog>
    <HuilanDialog title="在线预览" :visible.sync="excelVisible" append-to-body width="600px"
      custom-class="upload-image-dialog" v-if="excelVisible" top="5vh">
      <div v-html="tableContainerHtml" style="width: 100%;overflow-y: auto;height: 80vh;" class="dialog-table"></div>
    </HuilanDialog>
  </div>
</template>
<script>
import QSGDrawer from "@/components/QSGDrawer/index";
import { aiModelDataList, aiModelDataDelete, aiModelTrainingLogList, aiModelDataSubmit, aiModelDataExport, trainingStatus } from "@/api/configure/intelligentClassification";
import { baseURL } from "@/api/common";
import serviceList from '@/config/serviceList'
const { ai } = serviceList
export default {
  name: "trainingRecords",
  components: {
    QSGDrawer,
  },
  data() {
    return {
      parentId: undefined,
      dataInTitle: '导入数据集',
      form: {},
      trainingRecordsVisible: false,
      visible: false,
      downUrl: `${baseURL}template/数据集导入模板.xlsx`,
      classifyId: '',
      selectionList: [],
      trainData: [],
      trainDisabled: false,
      excelUrl: '',
      excelVisible: false,
      exceTit: '',
      tableContainerHtml: '',
      loadingBtn: {
        export: false,
        update: false,
        del: false,
      },
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      trainLoding: false,
      searchForm: {
        dataOldName: "",
      },
      searchFieldList: [
        {
          prop: "dataOldName",
          placeholder: "请输入数据集名称",
        },
      ],
      data: [
        {
          id: 10,
          name: '事件1',
          timeLine: 50,
          comment: '无'
        },
        {
          id: 1,
          name: '事件1',
          timeLine: 100,
          comment: '无',
        }
      ],
      option: {
        tip: false,
        headerAlign: 'left',
        align: 'left',
        border: true,
        index: false,
        rowKey: 'id',
        rowParentKey: 'parentId',
        editBtn: false,
        delBtn: false,
        addBtn: false,
        refreshBtn: false,
        columnBtn: false,
        searchShowBtn: false,
        dialogWidth: "40%",
        dialogType: "drawer",
        dialogCustomClass: "huilan-drawer-form",
        updateBtnIcon: ' ',
        cancelBtnIcon: ' ',
        saveBtnIcon: ' ',
        addBtnIcon: ' ',
        menuWidth: 180,
        selection: true,
        page: {
          current: 1,
          size: 10,
          total: 0,
        },
        // defaultExpandAll:true,
        column: [
          {
            label: '数据集名称',
            prop: 'dataOldName',
            overflows: true,
            align: 'left',
            span: 24,
          },
          {
            label: '条目',
            prop: 'dataNum',
            span: 24,
            width: 100,
          },
          {
            label: '上传时间',
            prop: 'createTime',
            width: 160,
            span: 24,
          },
          {
            label: '状态',
            prop: 'status',
            width: 100,
            span: 24,
            dicData: [
              {
                label: '未训练',
                value: 0
              },
              {
                label: '已训练',
                value: 1
              },
              {
                label: '训练中',
                value: 2
              }
            ]
          },
        ],
      },
      optionForm: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 90,
        updateBtnIcon: ' ',
        cancelBtnIcon: ' ',
        saveBtnIcon: ' ',
        addBtnIcon: ' ',
        column: [
          {
            label: '',
            prop: 'aggregateText',
            span: 24,
            labelWidth: 0,
          },
          {
            label: '',
            prop: 'file',
            dataType: 'object',
            type: 'upload',
            labelWidth: 0,
            propsHttp: {
            },
            data: {
              classifyId: '',
            },
            accept: ".xls,.xlsx",
            span: 24,
            action: `${baseURL}api/${ai}/aiModelData/import`,
            tip: '上传文件大小不超过30M',
            fileSize: 30 * 1024,
            rules: [
              {
                required: true,
                message: '请输入分类名称',
                trigger: "blur",
              },
            ],
          },
        ]
      },
      optionReport: {
        headerAlign: 'center',
        align: 'center',
        border: true,
        index: false,
        rowKey: 'id',
        rowParentKey: 'parentId',
        editBtn: false,
        delBtn: false,
        addBtn: false,
        refreshBtn: false,
        columnBtn: false,
        searchShowBtn: false,
        updateBtnIcon: ' ',
        cancelBtnIcon: ' ',
        saveBtnIcon: ' ',
        addBtnIcon: ' ',
        menuWidth: 180,
        menu: false,
        labelAlign: 'left',
        // defaultExpandAll:true,
        column: [
          {
            label: '模型编号',
            prop: 'modelNum',
            span: 24,
            align: 'left',
            headerAlign: 'left',
          },
          {
            label: '创建时间',
            prop: 'createTime',
            span: 24,
            align: 'left',
            headerAlign: 'left',
          },
          {
            label: '训练状态',
            prop: 'status',
            span: 24,
            align: 'left',
            headerAlign: 'left',
            dicData: [
              {
                label: '训练中',
                value: 0
              },
              {
                label: '训练失败',
                value: 1
              },
              {
                label: '训练完成',
                value: 2
              },
            ]
          },
        ],
      },
    }
  },
  watch: {

  },
  computed: {

  },
  async mounted() {

  },
  methods: {
    init(classifyId) {
      this.classifyId = classifyId
      this.pageList(classifyId);
      this.requstname(classifyId)
    },
    pageList(classifyId) {
      const params = {
        current: this.page.currentPage,
        size: this.page.size,
        ...this.searchForm
      }
      const self = this;
      aiModelDataList({ classifyId, ...params }).then((res) => {
        self.page.total = res.data.data.total;
        self.data = res.data.data.records || [];
      });
    },
    getRowActions() {
      const list = [];
      const btnList = [
        {
          name: '查看',
          command: 'showView',
          auth: 'VIEW'
        },
        {
          name: '删除',
          command: 'remove',
          auth: 'DEL',
        },
        {
          name: '下载数据集',
          command: 'downSit',
          auth: 'DOWNSIT',
        }
      ];
      btnList.forEach(item => {
        if (item.auth) {
          list.push({
            name: item.name,
            command: item.command
          });
        }
      });
      return list;
    },
    handleRowCommand(command, row /*, index*/) {
      const self = this;
      switch (command) {
        case 'showView':
          self.showView(row);
          break;
        case 'showEdit':
          self.$refs.crud.rowEdit(row, row.$index);
          break;
        case 'remove':
          self.$refs.crud.rowDel(row, row.$index);
          break;
        case 'downSit':
          self.downSit(row, row.$index);
          break;
      }
    },
    async showView(row) {
      this.exceTit = row.dataNewName
      const excelUrl = baseURL.substr(0, baseURL.length - 1) + row.uploadUrl
      const file = await (await fetch(excelUrl)).arrayBuffer();
      const workbook = window.XLSX.read(file, { dense: true });
      const fileDataSource = workbook.Sheets[workbook.SheetNames[0]];
      const aoo = window.XLSX.utils.sheet_to_html(fileDataSource);
      this.excelVisible = true
      this.tableContainerHtml = aoo;
    },
    searchChange() {
      this.page.currentPage = 1;
      this.pageList(this.classifyId)
    },
    searchReset() {
      this.page.currentPage = 1;
      this.searchForm = {};
      this.pageList(this.classifyId)
    },
    plugAdd() {
      this.$refs.crud.rowAdd();
    },
    formClose() {
      this.$refs.form.resetForm()
      this.trainingRecordsVisible = false
    },
    ImportAggregate() {
      this.dataInTitle = '导入数据集'
      this.trainingRecordsVisible = true
      this.$refs.form.resetForm()
    },
    handleMouseEnter() {
      this.visible = true
      this.trainPageList()
    },
    trainPageList() {
      const self = this;
      self.trainLoding = true
      aiModelTrainingLogList({ ...this.page, classifyId: this.classifyId }).then((res) => {
        this.trainLoding = false
        self.trainData = res.data.data.records || [];
      });
    },
    downSit(row) {
      let baseUrl = baseURL.substr(0, baseURL.length - 1);
      window.open(`${baseUrl}` + row.uploadUrl)
    },
    uploadBefore(file, done, loading) {  // eslint-disable-line
      const excelFileColumn = this.findObject(this.optionForm.column, "file");
      excelFileColumn.data.classifyId = this.classifyId;
      if (file.name.indexOf('.xls') === -1 && file.name.indexOf('.xlsx') === -1) {
        this.$message.error('请上传xls、xlsx格式文件')
        loading()
        return false
      }
      setTimeout(() => {
        done();
      }, 1000);
    },
    uploadAfter(res, done) {
      if (res.success) {
        this.$message.success('导入成功')
        this.trainingRecordsVisible = false
        this.pageList(this.classifyId)
      } else {
        this.$message.error(res)
      }
      done();
    },
    rowDel(row) {
      this.publicDel(row.id)
    },
    selectionChange(list) {
      this.selectionList = list
    },
    publicDel(ids) {
      this.$confirm(this.$t("aicosCommon.mutiDeleteConfirmTip"), {
        confirmButtonText: this.$t("aicosCommon.confirmBtn"),
        cancelButtonText: this.$t("aicosCommon.cancelBtn"),
        type: "warning",
      })
        .then(() => {
          this.loadingBtn.del = true
          return aiModelDataDelete({ ids });
        })
        .then(() => {
          this.loadingBtn.del = false
          this.$message({
            type: "success",
            message: this.$t("aicosCommon.successOperate"),
          });
          // 数据回调进行刷新
          this.pageList(this.classifyId)
        });
    },
    delDataSit() {
      if (this.selectionList.length === 0) {
        this.$message({
          type: "error",
          message: "请选择要删除的数据集",
        });
        return;
      }
      const ids = this.selectionList.map((item) => item.id).join(",");
      this.publicDel(ids)
    },
    submitTrain() {
      const self = this
      if (this.selectionList.length === 0) {
        this.$message({
          type: "error",
          message: "请选择要训练数据",
        });
        return;
      }
      const ids = this.selectionList.map((item) => item.id).join(",");
      aiModelDataSubmit({ ids, classifyId: this.classifyId }).then(res => {
        if (res.data.success) {
          self.$message({
            type: "success",
            message: "提交成功",
          });
          self.requstname(this.classifyId)
          this.pageList(this.classifyId);
        }
      })
    },
    requstname(classifyId) {
      trainingStatus({ classifyId }).then(res => {
        if (res.data.success) {
          if (res.data.data === '0') {
            this.trainDisabled = true
          } else {
            this.trainDisabled = false
          }
        }
      })
    },
    exportDataSit() {
      if (this.selectionList.length === 0) {
        this.$message({
          type: "error",
          message: "请选择要导出数据",
        });
        return;
      }
      const ids = this.selectionList.map((item) => item.id).join(",");
      this.loadingBtn.export = true
      aiModelDataExport({ ids, classifyId: this.classifyId }).then(res => {
        if (res.status === 200) {
          const data = res.data;
          const fileName = res.headers['content-disposition'].split(';')[1].split('filename=')[1];
          //将fileName解码
          const fileNameDecode = decodeURIComponent(fileName);
          this.downFile(data, fileNameDecode);
          this.$message({
            type: "success",
            message: "导出成功",
          })
        }
        this.loadingBtn.export = false
      }).catch(error => {
        console.log(error)
        this.loadingBtn.export = false
      });
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.pageList(this.classifyId)
    },
    sizeChange(pageSize) {
      this.page.size = pageSize;
      this.page.currentPage = 1
      this.pageList(this.classifyId)
    },
  },
};
</script>

<style scoped lang="scss">
/deep/ .avue-crud__menu {
  min-height: 0;
}

/deep/ .el-dialog__body {
  padding-top: 20px;
}

// .dialog-table>table>tbody>tr>td:nth-child(1) {
.dialog-table /deep/ table>tbody>tr>td:nth-child(1){
  min-width: 200px;
}
</style>
